<template>
  <el-dialog
    :title="dataForm.featureId ? '修改' : '新增'"
    :close-on-click-modal="false"
    v-model="visible"
    width="600px"
    @close="closeDialog"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="100px"
      @keyup.enter.native="dataFormSubmit()"
    >
      <el-form-item label="五官名称" prop="featureName">
        <el-input
          v-model="dataForm.featureName"
          placeholder="请输入五官名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="五官类型" prop="featureType">
        <el-select v-model="dataForm.featureType" placeholder="请选择五官类型">
          <el-option label="左眼" :value="1" />
          <el-option label="右眼" :value="2" />
          <el-option label="左眉" :value="3" />
          <el-option label="右眉" :value="4" />
          <el-option label="左腮红" :value="5" />
          <el-option label="右腮红" :value="6" />
          <el-option label="嘴巴" :value="7" />
          <el-option label="发型" :value="8" />
        </el-select>
      </el-form-item>

      <el-form-item label="五官图片" prop="featureImageUrl">
        <pic-upload v-model="dataForm.featureImageUrl" />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="X轴偏移" prop="offsetX">
            <el-input-number
              v-model="dataForm.offsetX"
              :precision="2"
              :step="0.1"
              :min="-100"
              :max="100"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="Y轴偏移" prop="offsetY">
            <el-input-number
              v-model="dataForm.offsetY"
              :precision="2"
              :step="0.1"
              :min="-100"
              :max="100"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="缩放比例" prop="scale">
            <el-input-number
              v-model="dataForm.scale"
              :precision="2"
              :step="0.1"
              :min="0.1"
              :max="10"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="旋转角度" prop="rotation">
            <el-input-number
              v-model="dataForm.rotation"
              :precision="2"
              :step="1"
              :min="-360"
              :max="360"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="图层顺序" prop="layerOrder">
        <el-input-number
          v-model="dataForm.layerOrder"
          :min="1"
          :max="100"
          controls-position="right"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="透明度" prop="opacity">
        <el-slider
          v-model="dataForm.opacity"
          :min="0"
          :max="1"
          :step="0.1"
          show-input
          show-stops
        />
      </el-form-item>

      <el-form-item label="混合模式" prop="blendMode">
        <el-select v-model="dataForm.blendMode" placeholder="请选择混合模式">
          <el-option label="正常" value="normal" />
          <el-option label="正片叠底" value="multiply" />
          <el-option label="滤色" value="screen" />
          <el-option label="叠加" value="overlay" />
          <el-option label="柔光" value="soft-light" />
          <el-option label="强光" value="hard-light" />
        </el-select>
      </el-form-item>

      <el-form-item label="可见性" prop="visible">
        <el-radio-group v-model="dataForm.visible">
          <el-radio :label="true">可见</el-radio>
          <el-radio :label="false">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import $cookie from 'vue-cookies'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataFormRef = ref(null)

const dataForm = reactive({
  featureId: 0,
  featureName: '',
  featureType: 1,
  featureImageUrl: '',
  offsetX: 0,
  offsetY: 0,
  scale: 1.0,
  rotation: 0.0,
  layerOrder: 1,
  visible: true,
  opacity: 1.0,
  blendMode: 'normal',
  status: 1
})

const dataRule = {
  featureName: [
    { required: true, message: '五官名称不能为空', trigger: 'blur' },
    { max: 50, message: '五官名称长度不能超过50个字符', trigger: 'blur' }
  ],
  featureType: [
    { required: true, message: '请选择五官类型', trigger: 'change' }
  ],
  featureImageUrl: [
    { required: true, message: '请上传五官图片', trigger: 'change' }
  ],
  scale: [
    { required: true, message: '缩放比例不能为空', trigger: 'blur' }
  ],
  layerOrder: [
    { required: true, message: '图层顺序不能为空', trigger: 'blur' }
  ],
  opacity: [
    { required: true, message: '透明度不能为空', trigger: 'blur' }
  ],
  blendMode: [
    { required: true, message: '请选择混合模式', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 上传配置
const uploadUrl = http.adornUrl('/file/upload')
const uploadHeaders = reactive({
  Authorization: $cookie.get('Authorization')
})

const init = (val) => {

  visible.value = true
  nextTick(() => {
    dataFormRef.value?.resetFields()
    if (val) {
      // 获取详情
      http({
        url: http.adornUrl(`/admin/faceFeature/info/${val.featureId}`),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        Object.assign(dataForm, data)
      })
    } else {
      // 重置表单
      Object.assign(dataForm, {
        featureId: 0,
        featureName: '',
        featureType: 1,
        featureImageUrl: '',
        offsetX: 0,
        offsetY: 0,
        scale: 1.0,
        rotation: 0.0,
        layerOrder: 1,
        visible: true,
        opacity: 1.0,
        blendMode: 'normal',
        status: 1
      })
    }
  })
}

defineExpose({ init })

/**
 * 表单提交
 */
const dataFormSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    if (!valid) {
      return
    }

    const url = dataForm.featureId ? '/admin/faceFeature' : '/admin/faceFeature'
    const method = dataForm.featureId ? 'put' : 'post'

    http({
      url: http.adornUrl(url),
      method: method,
      data: http.adornData({
        featureId: dataForm.featureId || undefined,
        featureName: dataForm.featureName,
        featureType: dataForm.featureType,
        featureImageUrl: dataForm.featureImageUrl,
        offsetX: dataForm.offsetX,
        offsetY: dataForm.offsetY,
        scale: dataForm.scale,
        rotation: dataForm.rotation,
        layerOrder: dataForm.layerOrder,
        visible: dataForm.visible,
        opacity: dataForm.opacity,
        blendMode: dataForm.blendMode,
        status: dataForm.status
      })
    })
      .then(() => {
        ElMessage({
          message: '操作成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      })
  })
}

/**
 * 关闭对话框
 */
const closeDialog = () => {
  dataFormRef.value?.resetFields()
}

/**
 * 上传成功处理
 */
const handleUploadSuccess = (response) => {
  if (response && response.code === 0) {
    dataForm.featureImageUrl = response.url || response.data
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(response?.msg || '上传失败')
  }
}

/**
 * 上传前检查
 */
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

/**
 * 预览图片
 */
const previewImage = () => {
  if (dataForm.featureImageUrl) {
    window.open(dataForm.featureImageUrl, '_blank')
  }
}

/**
 * 删除图片
 */
const removeImage = () => {
  ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    dataForm.featureImageUrl = ''
    ElMessage.success('删除成功')
  }).catch(() => {})
}
</script>

<style scoped lang="scss">
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);

  &:hover {
    border-color: var(--el-color-primary);
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
    line-height: 120px;
  }
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  border-radius: 6px;
  border: 1px solid #ebeef5;
}

.avatar-actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

.el-input-number {
  width: 100%;
}

.el-slider {
  width: 100%;
}
</style>
